﻿using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Ordinaire.Tool
{
    public class Reflection
    {
        /// <summary>
        /// Returns the column attribute of specified instance field.
        /// </summary>
        /// <param name="instance">instance</param>
        /// <param name="fieldName">field name</param>
        /// <returns>column attribute name</returns>
        public static string GetColumnAttribute(object instance, string fieldName)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(String.Format(ExceptionMessage.IsNullOrEmpty, "instance"));
            }

            Type type       = instance.GetType();
            PropertyInfo pi = type.GetProperty(fieldName);
            object[] info   = pi.GetCustomAttributes(typeof(ColumnAttribute), true);

            if (info != null && info.Length == 1)
            {
                ColumnAttribute attribute = (ColumnAttribute)info[0];
                return attribute.Name;
            }

            return String.Empty;
        }

        /// <summary>
        /// Returns the table attribute of specified instance.
        /// </summary>
        /// <param name="instance">instance</param>
        /// <returns>table attribute name</returns>
        public static string GetTableAttribute(object instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(String.Format(ExceptionMessage.IsNullOrEmpty, "instance"));
            }

            Type type     = instance.GetType();
            object[] info = type.GetCustomAttributes(typeof(TableAttribute), false);

            if (info != null && info.Length == 1)
            {
                TableAttribute attribute = (TableAttribute) info[0];
                return attribute.Name;
            }

            return String.Empty;
        }
    }
}
